/**
 * 网络线程测试
 * 
 * 用途：测试ApiClient修复后的网络请求是否正确在后台线程处理
 * 方法：模拟网络请求，验证响应处理不会在主线程执行
 * 原理：使用协程和线程检查确保网络操作在IO线程执行
 */
package com.example.brain_wave.test

import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.example.brain_wave.bluetooth.api.ApiClient
import com.example.brain_wave.bluetooth.model.TabletBrainWaveData
import kotlinx.coroutines.*
import org.junit.Before
import org.junit.Test
import org.junit.Assert.*

class NetworkThreadTest {
    
    private lateinit var apiClient: ApiClient
    private lateinit var context: Context
    
    @Before
    fun setUp() {
        context = ApplicationProvider.getApplicationContext()
        apiClient = ApiClient(context)
        
        // 配置测试API
        apiClient.setBaseUrl("http://localhost:8080")
        apiClient.setEndpoint("/api/brainwave/data")
    }
    
    @Test
    fun testNetworkResponseHandledInBackgroundThread() = runBlocking {
        println("🧵 测试网络响应是否在后台线程处理")
        
        var responseThreadName: String? = null
        var errorThreadName: String? = null
        
        // 设置回调来捕获线程信息
        apiClient.setOnSuccess { response ->
            responseThreadName = Thread.currentThread().name
            println("✅ 成功回调执行线程: $responseThreadName")
        }
        
        apiClient.setOnError { error ->
            errorThreadName = Thread.currentThread().name
            println("❌ 错误回调执行线程: $errorThreadName")
        }
        
        // 创建测试数据
        val testData = TabletBrainWaveData(
            session_id = "test_session_${System.currentTimeMillis()}",
            room_id = "test_room",
            timestamp = System.currentTimeMillis(),
            raw_value = listOf(100, 200, 150, 180, 120),
            delta = 120000,
            theta = 85000,
            low_alpha = 45000,
            high_alpha = 32000,
            low_beta = 28000,
            high_beta = 15000,
            low_gamma = 8000,
            mid_gamma = 5000,
            attention = 75,
            meditation = 60,
            poor_signal = 0,
            blink_strength = 50
        )
        
        // 发送数据
        apiClient.sendBrainWaveData(testData)
        
        // 等待响应
        delay(3000)
        
        // 验证回调是否在主线程执行（这是期望的行为）
        if (responseThreadName != null) {
            println("📊 响应处理线程: $responseThreadName")
            assertTrue("成功回调应该在主线程执行", responseThreadName == "main")
        }
        
        if (errorThreadName != null) {
            println("📊 错误处理线程: $errorThreadName")
            assertTrue("错误回调应该在主线程执行", errorThreadName == "main")
        }
        
        // 至少应该有一个回调被触发
        assertTrue("应该有回调被触发", responseThreadName != null || errorThreadName != null)
        
        println("✅ 网络线程测试完成")
    }
    
    @Test
    fun testNoNetworkOnMainThreadException() = runBlocking {
        println("🚫 测试是否避免了主线程网络异常")
        
        var exceptionCaught = false
        var callbackExecuted = false
        
        // 设置回调
        apiClient.setOnSuccess { response ->
            callbackExecuted = true
            println("✅ 成功回调执行，无异常")
        }
        
        apiClient.setOnError { error ->
            callbackExecuted = true
            println("❌ 错误回调执行: $error")
            // 检查是否是NetworkOnMainThreadException
            if (error.contains("NetworkOnMainThreadException")) {
                exceptionCaught = true
            }
        }
        
        // 创建测试数据
        val testData = TabletBrainWaveData(
            session_id = "exception_test_${System.currentTimeMillis()}",
            room_id = "test_room",
            timestamp = System.currentTimeMillis(),
            raw_value = listOf(100, 200, 150),
            delta = 120000,
            theta = 85000,
            low_alpha = 45000,
            high_alpha = 32000,
            low_beta = 28000,
            high_beta = 15000,
            low_gamma = 8000,
            mid_gamma = 5000,
            attention = 75,
            meditation = 60,
            poor_signal = 0,
            blink_strength = 50
        )
        
        // 发送数据
        apiClient.sendBrainWaveData(testData)
        
        // 等待响应
        delay(3000)
        
        // 验证结果
        assertTrue("应该有回调被执行", callbackExecuted)
        assertFalse("不应该出现NetworkOnMainThreadException", exceptionCaught)
        
        println("✅ 主线程网络异常避免测试完成")
    }
}